package org.lionsoul.websnail.downloader.http;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * Factory to generate self defined HttpClient instance
 *
 * @author chenxin<chenxin619315 @ gmail.com>
 */
public class HttpClientBuilder {
	private HttpClientBuilder()
	{

	}

	public static org.apache.http.impl.client.HttpClientBuilder getDefaultHttpClientBuilder()
	{
		return getHttpClientBuilder(1000, 3);
	}

	/**
	 * create a custom HttpClient
	 * with defined retryHandler & KeepAliveStrategy
	 * and RedirectStrategy
	 * <p>
	 * ConnectionManager of course
	 *
	 * @return CloseableHttpClient
	 */
	public static org.apache.http.impl.client.HttpClientBuilder getHttpClientBuilder(
			int httpConnectionPoolSize,
			int httpMaxRetryTimes)
	{
		//set the connection pool size
		Registry<ConnectionSocketFactory> reg =
				RegistryBuilder.<ConnectionSocketFactory>create()
						.register("http", PlainConnectionSocketFactory.INSTANCE)
						.register("https", SSLConnectionSocketFactory.getSocketFactory())
						.build();

		//create the PoolingHttpClient connection manager
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(reg);
		connectionManager.setDefaultMaxPerRoute(100);
		connectionManager.setMaxTotal(httpConnectionPoolSize);

		//Socket config
		SocketConfig socketConfig = SocketConfig.custom()
				.setSoKeepAlive(true)
				.setTcpNoDelay(true)
				.build();

		//override SocketConfig in HttpClientBuilder
		connectionManager.setDefaultSocketConfig(socketConfig);

		//http retry handler
		HttpClientRetryHandler retryHandler =
				new HttpClientRetryHandler(httpMaxRetryTimes, true);

		return HttpClients.custom()
				.setConnectionManager(connectionManager)
				.setDefaultSocketConfig(socketConfig)
				.setRetryHandler(retryHandler);
	}
}
